package top.xtcoder.xtpsd.core.file.header;

import java.io.FileInputStream;
import java.io.IOException;

import top.xtcoder.xtpsd.base.FileColorModel;
import top.xtcoder.xtpsd.core.file.header.vo.PsdFileHeader;
import top.xtcoder.xtpsd.utils.ByteUtil;

public class FileHeaderParse {
	public PsdFileHeader parse(FileInputStream fis) throws IOException {
		PsdFileHeader header = new PsdFileHeader();
		byte[] bsSign = new byte[4];
		fis.read(bsSign);
		String signature = new String(bsSign);
		header.setSignature(signature);
		
		byte[] bsVersion = new byte[2];
		fis.read(bsVersion);
		String version = bsVersion[0] + "" + bsVersion[1];
		header.setVersion(version);
		
		byte[] bsReserved = new byte[6];
		fis.read(bsReserved);
		int reserved = ByteUtil.bytesToInt(bsReserved);
		header.setReserved(reserved);
		
		byte[] bsNumberChannels = new byte[2];
		fis.read(bsNumberChannels);
		int numberChannels = ByteUtil.bytesToInt(bsNumberChannels);
		header.setChannelsNumber(numberChannels);
		
		byte[] bsHeight = new byte[4];
		fis.read(bsHeight);
		int height = ByteUtil.bytesToInt(bsHeight);
		header.setHeight(height);
		
		byte[] bsWidth = new byte[4];
		fis.read(bsWidth);
		int width = ByteUtil.bytesToInt(bsWidth);
		header.setWidth(width);
		
		byte[] bsDepth = new byte[2];
		fis.read(bsDepth);
		int depth = ByteUtil.bytesToInt(bsDepth);
		header.setDepth(depth);
		
		byte[] bsColorModel = new byte[2];
		fis.read(bsColorModel);
		int colorModel = ByteUtil.bytesToInt(bsColorModel);
		header.setColorModel(parseColorModel(colorModel));
		
		return header;
	}
	
	private FileColorModel parseColorModel(int colorModel) {
		switch(colorModel) {
			case 0:
				return FileColorModel.Bitmap;
			case 1:
				return FileColorModel.Grayscale;
			case 2:
				return FileColorModel.Indexed;
			case 3:
				return FileColorModel.RGB;
			case 4:
				return FileColorModel.CMYK;
			case 7:
				return FileColorModel.Multichannel;
			case 8:
				return FileColorModel.Duotone;
			case 9:
				return FileColorModel.Lab;
		}
		return null;
	}
}
